<template>
    <div style="height: 100%" :class="[menuLocationClass,themeClass,systemClass]">
        <Layout class="main" style="height: 100%" v-if="!forceChangePass&&!target">
            <Sider v-if="isLeftMenu"  :collapsed-width="60" :style="{overflow: 'auto',paddingTop:'60px'}" :width="200" class="left-sider" collapsible
                   hide-trigger
                   v-model="collapsed">
                <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
                <div class="logo-con" style="position: fixed;top: 0">
                    <img :src="leftTopMaxLogo" style="width: 194px" key="max-logo" v-show="!collapsed"/>
                    <img :src="minLogo" style="width: auto" key="min-logo" v-show="collapsed"/>
                </div>
                <side-menu  :active-name="activeName" :collapsed="collapsed" :menu-list="menuList"
                           @on-select="turnToPage"
                           accordion ref="sideMenu">
                </side-menu>
            </Sider>
            <Layout>
                <Header class="header-con">
                    <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
                        <div class="custom-content-con-left" slot="left" v-if="isTopMenu">
                            <div class="topMenuLogo">
                                <img :src="maxLogo"  @click="linkHome"/>
                            </div>
                            <div class="topMenu">
                                <topMenu :icon-size="24" :active-name="activeName" :menu-list="menuList" @on-select="turnToPage"/>
                            </div>
                        </div>
                        <div class="custom-content-con-right" slot="right">
                            <user :user-avatar="userHeadImg" :username="username"/>
                            <LookScreen style="margin-right: 10px;"></LookScreen>
                            <fullscreen style="margin-right: 10px;" v-model="isFullscreen"/>
                            <span v-for="(item) in topHeaders">
                                <component :is="item" style="margin-right: 10px;"></component>
                            </span>
                        </div>
                    </header-bar>
                    <div class="tag-nav-wrapper" v-if="isTopMenu">
                        <tags-nav :list="tagNavList" :value="currentTag" @input="handleClick"
                                  @on-close="handleCloseTag"/>
                    </div>
                </Header>
                <div class="head_padding"></div>
                <Content class="main-content-con">
                    <Layout class="main-layout-con">
                        <template v-if="isLeftMenu">
                        <Affix :offset-top="60">
                            <div class="tag-nav-wrapper">
                                <tags-nav :list="tagNavList" :value="currentTag" @input="handleClick"
                                          @on-close="handleCloseTag"/>
                            </div>
                        </Affix>
                        </template>
                        <Content class="content-wrapper">
                            <div :style="waterMarkStyle" v-watermark="waterMark">
                            </div>
                            <lease-keep-alive :updateComponentsKey="setKey" ref="keepAlive">
                                <router-view :key="key"></router-view>
                            </lease-keep-alive>
                            <div>
                                <LeaseIframe
                                    :key="item.id"
                                    :url="item.meta.url"
                                    v-for="item in iframeList"
                                    v-show="$route.name === item.name"
                                />
                            </div>
                            <ABackTop :duration="50" ref="backTop" :bottom="80" :height="100" :right="50" :container="isTopMenu?'':'.content-wrapper'"></ABackTop>
                        </Content>
                    </Layout>
                </Content>
            </Layout>
        </Layout>
        <div style="padding-top: 100px" v-else-if="forceChangePass">
            <Row align="middle" style="height: 100%" type="flex">
                <Col offset="7" span="10">
                    <ChangePass title="您的密码已到期请修改密码"/>
                </Col>
            </Row>
        </div>
        <div style="padding-top: 100px" v-else-if="target">
            <AutoOpen></AutoOpen>
        </div>
    </div>
</template>
<script>
    import SideMenu from './components/menu/side-menu'
    import HeaderBar from './components/header-bar'
    import TagsNav from './components/tags-nav'
    import User from './components/user'
    import ABackTop from './components/a-back-top'
    import Fullscreen from './components/fullscreen'
    import LookScreen from './components/lockscreen/lockscreen'
    import AutoOpen from './components/auto-open/Auto-open'
    import {mapActions, mapGetters} from 'vuex'
    import {fullPath} from "@/libs/lazyLoading"
    import {
        getDynamicOpenTab,
        getNewTagList,
        getTagNavListFromSessionStorage,
        routeEqual,
        setDynamicOpenTab
    } from '@/libs/menu/util'
    import minLogo from '@/assets/images/logo-min-gwt.png'
    import maxLogo from '@/assets/images/logo1.png'
    import leftTopMaxLogo from '@/assets/images/logo-left-top.png'
    import LeaseKeepAlive from '_c/keep-alive/LeaseKeepAlive'
    import LeaseIframe from '_c/iframe/iframe'
    import ChangePass from './components/change-pass/change-pass'
    import {getStore} from '@/libs/utils/store';
    import {validatenull} from '@/libs/utils/validate'
    import topMenu from './components/menu/top-menu/top-menu'
    import Constants from "@/const/common/Constants";
    import {getSysTime} from "_p/basic/api/system-date";
    import moment from 'moment'
    import config from '@/config'

    export default {
        name: 'Main',
        components: {
            SideMenu,
            topMenu,
            HeaderBar,
            TagsNav,
            Fullscreen,
            LookScreen,
            User,
            ABackTop,
            LeaseKeepAlive,
            LeaseIframe,
            ChangePass,
            AutoOpen
        },
        data() {
            return {
                collapsed: false,
                minLogo,
                maxLogo,
                leftTopMaxLogo,
                isFullscreen: false,
                activeName: '',
                refreshTime: -1,
                ssoRefreshTime:-1,
                userHeadImg: require('@/assets/default-user-head.png'),
                menuTheme: 'light',
                currentTag: {
                    name: '',
                    params: {},
                    query: {},
                    meta: {}
                }
            }
        },
        computed: {
            ...mapGetters(['expires_in','sso_access_token', 'userInfo', 'dynamicTab', 'forceChangePass','lastAccessTime']),
            isLeftMenu(){
                return _AFS_PROJECT_CONFIG.menuLocation=='left';
            },
            target(){
                let _target = getStore({name:Constants.afs_login_target_key});
                if(_target){
                    return true;
                }
                return false;
            },
            topHeaders(){
               let topHeader  = [];
                if(_AFS_PROJECT_CONFIG.topHeaderComponent){
                    let tempArray =_AFS_PROJECT_CONFIG.topHeaderComponent;
                    tempArray.forEach(comPath=>{
                        topHeader.push(fullPath(comPath));
                    })
                }
                return topHeader;
            },
            isTopMenu(){
                return _AFS_PROJECT_CONFIG.menuLocation=='top';
            },
            // /不同主题下的class
            themeClass(){
                let cls = 'theme_'
                if(_AFS_PROJECT_CONFIG.theme !== undefined) {
                    cls += _AFS_PROJECT_CONFIG.theme;
                }
                return cls;
            },
            // 不同定位下的class
            menuLocationClass(){
                let cls = 'menuLocation_';
                if(_AFS_PROJECT_CONFIG.menuLocation !== undefined) {
                    cls += _AFS_PROJECT_CONFIG.menuLocation;
                }
                return cls;
            },
            // 不同系统的 class
            systemClass(){
                let cls = 'system_';
                let name = config.getProjectName();
                if(name !== undefined) {
                    cls += name;
                }
                return cls;
            },
            username() {
                return this.userInfo.userRealName;
            },
            userId() {
                return this.userInfo.id;
            },
            tagNavList() {
                return this.$store.state.menu.tagNavList
            },
            menuList() {
                return this.$store.getters.menuList
            },
            local() {
                return this.$store.state.menu.local
            },
            hasReadErrorPage() {
                return this.$store.state.menu.hasReadErrorPage
            },
            iframeList() {
                return this.$store.state.menu.tagNavList.filter(item => {
                    if (item && item.meta && item.meta.url != null && item.meta.url != '') {
                        return true
                    }
                    return false;
                })
            },
            key() {
                return this.$route.name;
            },
            waterMarkStyle() {
                return {
                    height: 'calc(100% - 100px)',
                    width: this.collapsed ? 'calc(100% - 60px)' : 'calc(100% - 220px)',
                    position: 'absolute',
                    top: '100px',
                    left: this.collapsed ? '60px' : '220px',
                    zIndex: 99999,
                    pointerEvents: 'none'
                }
            },
            waterMark() {
                return {
                    text: this.userInfo.username + '-' + this.userInfo.userRealName
                }
            }
        },
        methods: {
            ...mapActions(['LogOut']),
            backToTop(){
              this.$refs.backTop.back();
            },
            turnToPage(route) {

                let {name, params, query} = {}
                if (typeof route === 'string') {
                    name = route
                } else {
                    name = route.name
                    params = route.params
                    query = route.query
                }
                if (this.$route.name != name) {
                    this.$router.push({
                        name,
                        params,
                        query
                    })
                }
            },
            linkHome(){
                this.$router.push({
                    name: "home_index"
                }).catch(err => {err});
            },
            handleCollapsedChange(state) {
                this.collapsed = state
            },
            handleCloseTag(res, type, route) {
                if (type !== 'others') {
                    if (type === 'all') {
                        setDynamicOpenTab([])
                        this.turnToPage(this.$config.getHomeName())
                    } else {
                        if (routeEqual(this.currentTag, route)) {
                            this.$store.commit('closeTag', route);
                        }else{
                            this.$store.commit('closeOtherTag', route);
                        }
                    }
                } else {
                    setDynamicOpenTab(getDynamicOpenTab().filter(tab => {
                        return route.name === tab.name
                    }))
                }
                this.$store.commit('setTagNavList', res)
            },
            handleClick(item) {
                this.turnToPage(item)
            },
            refreshToken() {
                this.refreshTime = setInterval(() => {
                    const token = getStore({
                        name: 'access_token'
                    });
                    if(this.lastAccessTime&&(Date.now()-this.lastAccessTime)/1000/60>this.userInfo.autoLogOutTime){
                        clearInterval(this.refreshTime)
                        this.$Message.error({
                            background: true,
                            content: '您已经[ '+this.userInfo.autoLogOutTime+' ]分钟没操作系统，将自动退出',
                            duration: 3,
                            onClose:()=>{
                                this.LogOut().then(() => {
                                    this.$store.commit("clearTagNavList");
                                    let tenantId = this.$store.getters.tenantId;
                                    if (tenantId) {
                                        this.$router.push({
                                            path: '/' + tenantId + '/login'
                                        });
                                    } else {
                                        this.$router.push({
                                            name: "login_base"
                                        });
                                    }
                                })
                            }
                        })
                        return ;
                    }
                    if (validatenull(token)) {
                        return;
                    }

                    if ((this.expires_in - Date.now()) / 1000 <= 30 && !this.refreshLock) {
                        this.refreshLock = true;
                        this.$store
                            .dispatch('RefreshToken')
                            .catch(() => {
                                clearInterval(this.refreshTime)
                            });
                        this.refreshLock = false
                    }
                }, 10000);
                if (this.sso_access_token&&this.sso_access_token!=='') {
                    this.ssoRefreshTime = setInterval(()=>{
                        this.refreshLock = true;
                        this.$store
                            .dispatch('RefreshOssToken')
                            .catch(() => {
                                clearInterval(this.ssoRefreshTime)
                            });
                        this.refreshLock = false
                    }, 1000*60*5)
                }
            },
            setKey(key) {
                //目前不做任何操作
            }
        },
        watch: {
            '$route'(newRoute) {
                const {name, query, params, meta} = newRoute
                this.currentTag.name = name;
                this.currentTag.params = params;
                this.currentTag.query = query;
                this.currentTag.meta = meta;
                this.$store.commit('addTag', {
                    route: {name, query, params, meta},
                    type: 'push'
                });
                let openedName = newRoute.name, breadCrumbList = undefined;
                if (newRoute.meta.dynamicTab) {
                    let dynamicTabs = getDynamicOpenTab();
                    dynamicTabs.forEach(tab => {
                        if (tab.meta.name == newRoute.meta.name) {
                            if (!tab.meta.breadCrumbList) {
                                tab.meta.breadCrumbList = this.$store.getters.breadCrumbList
                                tab.meta.openedName = this.activeName;
                                openedName = this.activeName;
                                breadCrumbList = this.$store.getters.breadCrumbList;
                            } else {
                                openedName = tab.meta.openedName
                                breadCrumbList = tab.meta.breadCrumbList
                            }
                        }
                    })
                    setDynamicOpenTab(dynamicTabs)
                }

                this.activeName = openedName;
                this.$store.commit('setBreadCrumb', {route: newRoute, breadCrumbList: breadCrumbList});
                if(this.$refs.sideMenu){
                    this.$refs.sideMenu.updateOpenName(openedName)
                }
                this.$store.commit('setTagNavList', getNewTagList(this.tagNavList, newRoute));
                this.$refs['backTop'].reStoreScroll(name);
            },
            'dynamicTab.uuid'() {
                this.$nextTick(() => {
                    let tabIndex = this.dynamicTab.tabIndex;
                    const dynamicTabs = getDynamicOpenTab();
                    let dRouter = dynamicTabs.filter(tab => {
                        return tabIndex == tab.meta.dIndex;
                    })[0]
                    if (dRouter) {
                        this.turnToPage({name: dRouter.name, params: dRouter.meta.params, query: {}});
                    }
                })

            }
        },

        mounted() {

            /**
             * @description 初始化设置面包屑导航和标签导航
             */
            this.$store.commit('setTagNavList');
            this.$store.commit('setHomeRoute');
            this.$store.commit('updateRef', this.$refs.keepAlive);
            let {name, params, query, meta} = this.$route;
            let activeName = name;
            getTagNavListFromSessionStorage().forEach(tag => {
                if (tag.name == name) {
                    name = tag.name;
                    params = tag.meta.params;
                    query = tag.query;
                    meta = tag.meta;
                }
            })
            if (meta.dynamicTab) {
                getDynamicOpenTab().forEach(tag => {
                    if (tag.name === name) {
                        meta = tag.meta;
                        activeName = tag.meta.openedName;
                    }
                })
            }
            this.currentTag.name = name;
            this.currentTag.params = params;
            this.currentTag.query = query;
            this.currentTag.meta = meta;
            this.activeName = activeName;
            this.$store.commit('addTag', {route: {name, params, query, meta}});
            this.$store.commit('setBreadCrumb', {route: this.$route, breadCrumbList: meta.breadCrumbList});
            this.$store.commit('setLocal', this.$i18n.locale);
            // 设置初始语言
            // 如果当前打开页面不在标签栏中，跳到homeName页
            if (!this.tagNavList.find(item => item.name === this.$route.name)) {
                this.$router.push({
                    name: this.$config.getHomeName()
                })
            }
            this.$nextTick(() => {
                let dTabs = getDynamicOpenTab().filter(dynamicTab => {
                    return getTagNavListFromSessionStorage().filter(tab => {
                        return tab.name == dynamicTab.name;
                    }).length > 0;
                })
                setDynamicOpenTab(dTabs);
            })
        },
        created() {
            if (!this.userInfo.userRealName || this.userInfo.userRealName == '') {
                this.$store.dispatch('GetUserInfo')
            }
            this.refreshToken();
            this.$store.commit("setMainComponent",this);
            getSysTime().then(res => {
                if (res.code === "0000" && res.data) {
                    this.time = moment(res.data.bhDate).format('YYYY-MM-DD');
                    this.$store.commit('updateBatchDate',this.time);
                }
            })
        },
        destroyed() {
            clearInterval(this.refreshTime)
        }
    }
</script>
<style lang="less" scoped>
    @import './main.less';
</style>
<style lang="less">
.afs-header-transfer {
    top: 0;
}
.headDropdown {
    max-height: 500px;
}

.system_afsContract {
    .ivu-input[disabled],
    fieldset[disabled] .ivu-input,
    .ivu-select-disabled .ivu-select-selection {
        cursor: default !important;
        user-select: auto !important;
    }

    .ivu-input[disabled], .ivu-select-input[disabled] {
        color: #515a6e;
    }

    .ivu-radio-disabled .ivu-radio-inner:after {
        background-color: #515a6e;
    }
}
</style>
